package com.ruoyi.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.customer.domain.TRevieweCooperate;
import com.ruoyi.customer.domain.bo.TRevieweCooperateBo;
import com.ruoyi.customer.domain.vo.TRevieweCooperateVo;
import com.ruoyi.customer.mapper.TRevieweCooperateMapper;
import com.ruoyi.customer.service.ITRevieweCooperateService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 审件业绩合计单Service业务层处理
 *
 * @author ruoyi
 * @date 2023-10-09
 */
@RequiredArgsConstructor
@Service
public class TRevieweCooperateServiceImpl implements ITRevieweCooperateService {

    private final TRevieweCooperateMapper baseMapper;

    /**
     * 查询审件业绩合计单
     */
    @Override
    public TRevieweCooperateVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询审件业绩合计单列表
     */
    @Override
    public TableDataInfo<TRevieweCooperateVo> queryPageList(TRevieweCooperateBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TRevieweCooperate> lqw = buildQueryWrapper(bo);
        Page<TRevieweCooperateVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询审件业绩合计单列表
     */
    @Override
    public List<TRevieweCooperateVo> queryList(TRevieweCooperateBo bo) {
        LambdaQueryWrapper<TRevieweCooperate> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TRevieweCooperate> buildQueryWrapper(TRevieweCooperateBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TRevieweCooperate> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getRevieweId() != null, TRevieweCooperate::getRevieweId, bo.getRevieweId());
        lqw.eq(bo.getRevenue() != null, TRevieweCooperate::getRevenue, bo.getRevenue());
        lqw.eq(StringUtils.isNotBlank(bo.getRatio()), TRevieweCooperate::getRatio, bo.getRatio());
        lqw.eq(bo.getCreateId() != null, TRevieweCooperate::getCreateId, bo.getCreateId());
        lqw.eq(bo.getUserId() != null, TRevieweCooperate::getUserId, bo.getUserId());
        return lqw;
    }

    /**
     * 新增审件业绩合计单
     */
    @Override
    public Boolean insertByBo(TRevieweCooperateBo bo) {
        TRevieweCooperate add = BeanUtil.toBean(bo, TRevieweCooperate.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改审件业绩合计单
     */
    @Override
    public Boolean updateByBo(TRevieweCooperateBo bo) {
        TRevieweCooperate update = BeanUtil.toBean(bo, TRevieweCooperate.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TRevieweCooperate entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除审件业绩合计单
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public void saveByBoList(Long revieweId, String disType, Long userId, Long deptId, BigDecimal revenue,
                             List<TRevieweCooperate> cooperateBoList) {

        QueryWrapper<TRevieweCooperate> deleteWrapper = new QueryWrapper<>();
        deleteWrapper.eq("reviewe_id", revieweId);
        baseMapper.delete(deleteWrapper);

        if (CollectionUtils.isEmpty(cooperateBoList)) {
            // 防止为空 补偿一个创建人的合作单记录
            TRevieweCooperate tRevieweCooperate = new TRevieweCooperate();
            tRevieweCooperate.setCreateId(LoginHelper.getUserId());
            tRevieweCooperate.setRevieweId(revieweId);
            tRevieweCooperate.setUserId(userId);
            tRevieweCooperate.setRatio("100");
            tRevieweCooperate.setDeptId(deptId);
            tRevieweCooperate.setDisType(disType);
            // 1、按比例 2、指定金额
            if (!Objects.isNull(revenue)) {
                if (Objects.equals("1", disType)) {
                    tRevieweCooperate.setRevenue(getRevenue(revenue, tRevieweCooperate.getRatio()));
                } else {
                    tRevieweCooperate.setRevenue(revenue);
                }
            }
            baseMapper.insert(tRevieweCooperate);
            return;
        }

        //List<TRevieweCooperate> cooperates = new ArrayList<>();
        for (TRevieweCooperate tRevieweCooperateBo : cooperateBoList) {
            TRevieweCooperate tRevieweCooperate = new TRevieweCooperate();
            tRevieweCooperate.setCreateId(LoginHelper.getUserId());
            tRevieweCooperate.setRevieweId(revieweId);
            tRevieweCooperate.setUserId(tRevieweCooperateBo.getUserId());
            tRevieweCooperate.setRatio(tRevieweCooperateBo.getRatio());
            tRevieweCooperate.setDeptId(tRevieweCooperateBo.getDeptId());
            tRevieweCooperate.setDisType(disType);
            if (!Objects.isNull(revenue)) {
                if (Objects.equals("1", disType)) {
                    tRevieweCooperate.setRevenue(getRevenue(revenue, tRevieweCooperateBo.getRatio()));
                } else {
                    tRevieweCooperate.setRevenue(new BigDecimal(tRevieweCooperateBo.getRatio()));
                }
            }
            baseMapper.insert(tRevieweCooperate);
            //cooperates.add(tRevieweCooperate);
        }
        //baseMapper.insertBatch(cooperates);
    }

    private BigDecimal getRevenue(BigDecimal revenue, String ratio) {
        if (StringUtils.isNotBlank(ratio)) {
            return revenue.multiply(new BigDecimal(ratio)).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
        }
        return BigDecimal.ZERO;
    }
}
